<template>
  <div v-if="dynamicTags" class="flex flex-col space-y-3 ...">
    <div
      v-for="(item, index) in dynamicTags"
      :key="index"
      class="flex flex-col space-y-2 ..."
    >
      <div v-for="(value, key, keyIndex) in item" :key="keyIndex">
        <div class="flex space-x-6 ..." v-if="keyIndex == 0">
          <strong>{{ firstAttrName }}:</strong>
          <!-- <strong>{{ key }}:</strong> -->
          <el-tag
            type="info"
            closable
            @click="handleClick(index)"
            @close="firstClose(index)"
            >{{ value }}
          </el-tag>
        </div>
        <div class="flex gap-2" v-if="keyIndex == 1">
          <strong>{{ secondAttrName }}:</strong>
          <el-tag
            v-for="tag in value"
            :key="tag"
            :type="tagType"
            closable
            :disable-transitions="false"
            @close="handleClose(tag, index)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="item.inputVisible"
            ref="inputRefs"
            v-model="item.inputValue"
            class="max-w-fit"
            size="small"
            @keyup.enter="handleInputConfirm(index)"
            @blur="handleInputConfirm(index)"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput(index)"
          >
            + New Tag
          </el-button>
        </div>
      </div>
    </div>
    <div class="flex space-x-4 ...">
      <el-button type="primary" @click="addTag">添加 Tag</el-button>

      <el-button type="primary" @click="confirmTag">更新数据</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, computed, onMounted } from "vue";
import { ElInput } from "element-plus";
import type { InputInstance } from "element-plus";
import { ElMessageBox, ElMessage } from "element-plus";

const inputValue = ref("");

const inputVisible = ref(false);
const InputRef = ref<InputInstance>();

const props = defineProps({
  dynamicTags: {
    type: Array,
    default: () => ["Tag 1", "Tag 2", "Tag 3"],
  },
  tagType: {
    type: String,
    default: () => "primary",
  },
  firstAttrName: {
    type: String,
    default: () => "尺寸",
  },
  secondAttrName: {
    type: String,
    default: () => "属性",
  },
  firstAttr: {
    type: String,
    default: () => "size",
  },
  secondAttr: {
    type: String,
    default: () => "attr",
  },
});

//
const dynamicTags = ref(
  JSON.parse(props.dynamicTags).map((item) => ({
    ...item,
    inputVisible: false,
    inputValue: "",
  }))
);

// 将子组件的添加、删除等事件都传递给父组件
const emit = defineEmits([
  "handleClose",
  "handleInputConfirm",
  "confirmTag",
  "firstClose",
]);
const handleClose = (tag, index) => {
  // console.log("tag:", tag, "index:", index);
  // 找到目标对象
  const targetItem = dynamicTags.value[index];
  if (targetItem && targetItem.attr.includes(tag)) {
    // 从 attr 数组中移除目标标签
    const tagIndex = targetItem.attr.indexOf(tag);
    if (tagIndex !== -1) {
      targetItem.attr.splice(tagIndex, 1);
    } // 如果 attr 数组为空，可以选择移除整个对象或进行其他操作
    if (targetItem.attr.length === 0) {
      dynamicTags.value.splice(index, 1);
    }
    // 将数据传递给父组件
    emit("handleClose", dynamicTags.value);
  }
  // dynamicTags.value.attr.splice(dynamicTags[index].value.attr.indexOf(tag), 1);
  console.log("dynamicTags:", dynamicTags.value);
};
// 用于存储多个输入框的引用
const inputRefs = ref([]);
const showInput = (index) => {
  dynamicTags.value[index].inputVisible = true;
  console.log("dynamicTags:", dynamicTags.value);

  // inputRefs.value[index].focus();
};

const handleInputConfirm = (index) => {
  const inputValue = dynamicTags.value[index].inputValue.trim();
  if (inputValue) {
    const targetItem = dynamicTags.value[index];
    if (!targetItem.attr.includes(inputValue)) {
      targetItem.attr.push(inputValue);
    }
    dynamicTags.value[index].inputValue = "";
  }
  dynamicTags.value[index].inputVisible = false;
  // 将数据传递给父组件
  emit("handleInputConfirm", dynamicTags.value);
};

const addTag = () => {
  dynamicTags.value.push({
    size: "medium",
    attr: [],
    inputVisible: false,
    inputValue: "",
  });
};

const handleClick = (index) => {
  // 编辑
  ElMessageBox.prompt("请输入修改内容:", "修改Size", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    // inputPattern:
    //   /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    inputErrorMessage: "Invalid value",
  })
    .then(({ value }) => {
      dynamicTags.value[index].size = value;
      ElMessage({
        type: "success",
        message: `输入内容：${value}`,
      });
    })
    .catch(() => {
      ElMessage({
        type: "error",
        message: "取消输入",
      });
    });
};
// 确认后调整数据
const confirmTag = () => {
  console.log("dynamicTags:", dynamicTags.value);
  emit("confirmTag", dynamicTags.value);
};
//  删掉整个规格对象
const firstClose = (index) => {
  dynamicTags.value.splice(index, 1);
  emit("firstClose", dynamicTags.value);
};

// 获取属性名
const getFirstAttrName = () => {
  let firstObj = dynamicTags.value[0];
  if (Object.keys(firstObj).length > 0) {
    const keys = Object.keys(firstObj);
    console.log("keys:", keys);
  }
};

onMounted(() => {
  // 获取属性名
  // getFirstAttrName();
});
</script>
